{% extends "base.html" %}

{% block title %}游戏主界面 - VXBattle{% endblock %}

{% block content %}
<div class="row">
    <!-- 左侧：角色列表 -->
    <div class="col-lg-4 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-users me-2"></i>我的角色
                </h5>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#createCharacterModal">
                    <i class="fas fa-plus me-1"></i>创建角色
                </button>
            </div>
            <div class="card-body" id="characterList">
                <div class="text-center text-muted">
                    <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 右侧：挂机系统 -->
    <div class="col-lg-8">
        <div class="row">
            <!-- 当前角色状态 -->
            <div class="col-12 mb-4">
                <div class="card" id="currentCharacterCard" style="display: none;">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-user me-2"></i>当前角色状态
                        </h5>
                    </div>
                    <div class="card-body" id="currentCharacterInfo">
                        <!-- 角色信息将在这里显示 -->
                    </div>
                </div>
            </div>



            <!-- 挂机状态 -->
            <div class="col-12">
                <div class="card" id="idleStatusCard" style="display: none;">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-clock me-2"></i>挂机状态
                        </h5>
                    </div>
                    <div class="card-body" id="idleStatusInfo">
                        <!-- 挂机状态将在这里显示 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 创建角色模态框 -->
<div class="modal fade" id="createCharacterModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus me-2"></i>创建新角色
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createCharacterForm">
                    <div class="mb-3">
                        <label for="characterName" class="form-label">角色名称</label>
                        <input type="text" class="form-control" id="characterName" name="name" required 
                               minlength="2" maxlength="20" pattern="[\u4e00-\u9fa5a-zA-Z0-9_]+">
                        <div class="form-text">2-20个字符，支持中文、英文、数字和下划线</div>
                    </div>
                    <div class="mb-3">
                        <label for="characterClass" class="form-label">职业选择</label>
                        <select class="form-select" id="characterClass" name="character_class" required>
                            <!-- 职业选项将通过JavaScript动态加载 -->
                        </select>
                        <div class="form-text" id="classDescription">选择职业查看详细信息</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="createCharacterBtn">
                    <i class="fas fa-plus me-1"></i>创建角色
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentCharacterId = null;
let characters = [];
let characterClasses = [];
let updateInterval = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 首先加载角色职业模板
    loadCharacterClasses();
    
    // 然后加载角色列表
    loadCharacters();
    
    // 每30秒更新一次状态
    updateInterval = setInterval(function() {
        if (currentCharacterId) {
            updateCurrentCharacterStatus();
            updateIdleStatus();
        }
    }, 30000);
});

// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
    if (updateInterval) {
        clearInterval(updateInterval);
    }
});

// 加载角色列表
async function loadCharacters() {
    try {
        const response = await apiRequest('/api/characters', 'GET');
        if (response.success) {
            characters = response.characters;
            renderCharacters();
            
            // 如果有角色，默认选择第一个或保持当前选择
            if (characters.length > 0) {
                // 如果当前已选择角色不在列表中，则选择第一个
                if (!currentCharacterId || !characters.find(c => String(c.id) === String(currentCharacterId))) {
                    selectCharacter(characters[0].id);
                } else {
                    // 更新当前选中角色的信息
                    updateCurrentCharacterStatus();
                    updateIdleStatus();
                }
            } else {
                // 没有角色时，清空当前选择
                currentCharacterId = null;
                document.getElementById('currentCharacterCard').style.display = 'none';
                document.getElementById('idleStatusCard').style.display = 'none';
            }
        } else {
            document.getElementById('characterList').innerHTML = 
                '<div class="text-center text-muted"><p>暂无角色</p></div>';
            // 清空当前选择
            currentCharacterId = null;
            document.getElementById('currentCharacterCard').style.display = 'none';
            document.getElementById('idleStatusCard').style.display = 'none';
        }
    } catch (error) {
        document.getElementById('characterList').innerHTML = 
            '<div class="text-center text-danger"><p>加载失败</p></div>';
        console.error('加载角色列表失败:', error);
    }
}

// 渲染角色列表
function renderCharacters() {
    const container = document.getElementById('characterList');
    
    if (characters.length === 0) {
        container.innerHTML = `
            <div class="text-center text-muted p-4">
                <i class="fas fa-user-plus fa-3x mb-3"></i>
                <h6>暂无角色</h6>
                <p class="mb-3">请创建一个角色开始游戏</p>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createCharacterModal">
                    <i class="fas fa-plus me-1"></i>创建第一个角色
                </button>
            </div>
        `;
        return;
    }
    
    let html = '';
    characters.forEach(char => {
        const expPercent = (char.exp / char.exp_to_next_level * 100).toFixed(1);
        const statusIcon = char.is_idle ? 
            '<i class="fas fa-clock status-online" title="挂机中"></i>' : 
            '<i class="fas fa-user status-offline" title="空闲"></i>';
        
        html += `
            <div class="character-card card mb-2 ${String(currentCharacterId) === String(char.id) ? 'border-primary' : ''}" 
                 onclick="selectCharacter('${char.id}')" style="cursor: pointer;">
                <div class="card-body p-3">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="card-title mb-1">${char.name}</h6>
                            <small class="text-muted">${char.character_class} • 等级 ${char.level}</small>
                        </div>
                        <div class="text-end d-flex align-items-center">
                            ${statusIcon}
                            <button class="btn btn-sm btn-outline-danger ms-2" 
                                    onclick="event.stopPropagation(); deleteCharacter('${char.id}', '${char.name}')" 
                                    title="删除角色">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mt-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <small class="text-muted">经验</small>
                            <small class="text-muted">${formatExp(char.exp)}/${formatExp(char.exp_to_next_level)}</small>
                        </div>
                        <div class="progress" style="height: 6px;">
                            <div class="progress-bar" style="width: ${expPercent}%"></div>
                        </div>
                    </div>
                    <div class="mt-2 d-flex gap-1">
                        <button class="btn btn-sm btn-warning flex-fill" 
                                onclick="event.stopPropagation(); quickCollectRewards('${char.id}')" 
                                title="收集挂机收益">
                            <i class="fas fa-gift me-1"></i>收集收益
                        </button>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 选择角色
function selectCharacter(characterId) {
    console.log('选择角色，ID:', characterId, '类型:', typeof characterId);
    currentCharacterId = String(characterId); // 确保ID为字符串类型
    
    // 显示相关卡片
    document.getElementById('currentCharacterCard').style.display = 'block';
    document.getElementById('idleStatusCard').style.display = 'block';
    
    // 重新渲染角色列表以更新选中状态
    renderCharacters();
    
    // 更新角色状态和挂机信息
    updateCurrentCharacterStatus();
    updateIdleStatus();
    
    console.log('角色选择完成，当前角色ID:', currentCharacterId);
}

// 更新当前角色状态
function updateCurrentCharacterStatus() {
    if (!currentCharacterId) {
        document.getElementById('currentCharacterInfo').innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-user me-2"></i>请先选择一个角色
            </div>
        `;
        return;
    }
    
    console.log('查找角色，当前ID:', currentCharacterId, '角色列表:', characters.map(c => ({id: c.id, name: c.name})));
    const character = characters.find(c => String(c.id) === String(currentCharacterId));
    if (!character) {
        console.error('未找到角色信息，当前ID:', currentCharacterId, '可用角色:', characters);
        document.getElementById('currentCharacterInfo').innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-exclamation-circle me-2"></i>未找到角色信息 (ID: ${currentCharacterId})
            </div>
        `;
        return;
    }
    
    console.log('找到角色:', character.name);
    
    const expPercent = (character.exp / character.exp_to_next_level * 100).toFixed(1);
    const statusBadge = character.is_idle ? 
        '<span class="badge bg-success">挂机中</span>' : 
        '<span class="badge bg-secondary">空闲</span>';
    
    const html = `
        <div class="row">
            <div class="col-md-6">
                <h5>${character.name} ${statusBadge}</h5>
                <p class="text-muted mb-2">${character.character_class} • 等级 ${character.level}</p>
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-1">
                        <span>经验值</span>
                        <span>${formatExp(character.exp)}/${formatExp(character.exp_to_next_level)}</span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar" style="width: ${expPercent}%"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="row">
                    <div class="col-6">
                        <div class="text-center">
                            <div class="h4 text-primary">${character.attack}</div>
                            <small class="text-muted">攻击</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="text-center">
                            <div class="h4 text-success">${character.speed}</div>
                            <small class="text-muted">速度</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="text-center">
                            <div class="h4 text-info">${character.defense}</div>
                            <small class="text-muted">防御</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="text-center">
                            <div class="h4 text-warning">${character.hp}</div>
                            <small class="text-muted">生命值</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('currentCharacterInfo').innerHTML = html;
}



// 加载角色职业模板
async function loadCharacterClasses() {
    try {
        const response = await apiRequest('/api/character/classes');
        if (response.success) {
            characterClasses = response.classes;
            renderCharacterClasses();
        } else {
            console.error('加载职业模板失败:', response.message);
        }
    } catch (error) {
        console.error('加载职业模板失败:', error);
    }
}

// 渲染角色职业选项
function renderCharacterClasses() {
    const select = document.getElementById('characterClass');
    
    // 清空现有选项
    select.innerHTML = '<option value="">请选择职业</option>';
    
    // 职业图标映射
    const classIcons = {
        '战士': '⚔️',
        '法师': '🔮',
        '弓箭手': '🏹',
        '盗贼': '🗡️',
        '刺客': '🗡️',
        '牧师': '✨'
    };
    
    // 添加职业选项
    characterClasses.forEach(cls => {
        const icon = classIcons[cls.name] || '🎯';
        const option = document.createElement('option');
        option.value = cls.name;
        option.textContent = `${icon} ${cls.name} - ${cls.description}`;
        option.dataset.classData = JSON.stringify(cls);
        select.appendChild(option);
    });
    
    // 绑定职业选择事件
    select.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        if (selectedOption.dataset.classData) {
            const classData = JSON.parse(selectedOption.dataset.classData);
            updateClassDescription(classData);
        } else {
            document.getElementById('classDescription').textContent = '选择职业查看详细信息';
        }
    });
}

// 更新职业描述
function updateClassDescription(classData) {
    const description = document.getElementById('classDescription');
    const stats = classData.base_stats;
    const growth = classData.growth;
    
    description.innerHTML = `
        <strong>${classData.description}</strong><br>
        <small class="text-muted">
            基础属性: HP ${stats.hp} | MP ${stats.mp} | 攻击 ${stats.attack} | 防御 ${stats.defense} | 速度 ${stats.speed}<br>
            成长: HP +${growth.hp} | MP +${growth.mp} | 攻击 +${growth.attack} | 防御 +${growth.defense} | 速度 +${growth.speed}
        </small>
    `;
}



// 更新挂机状态
async function updateIdleStatus() {
    if (!currentCharacterId) {
        document.getElementById('idleStatusInfo').innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-user-clock me-2"></i>请先选择一个角色
            </div>
        `;
        return;
    }
    
    try {
        const response = await apiRequest(`/api/idle/status/${currentCharacterId}`, 'GET');
        
        if (response.success) {
            const idleData = response.idle_data;
            renderIdleStatus(idleData);
        } else {
            document.getElementById('idleStatusInfo').innerHTML = `
                <div class="text-center text-muted">
                    <i class="fas fa-exclamation-circle me-2"></i>${response.message}
                </div>
            `;
        }
    } catch (error) {
        console.error('更新挂机状态失败:', error);
        document.getElementById('idleStatusInfo').innerHTML = `
            <div class="text-center text-danger">
                <i class="fas fa-exclamation-circle me-2"></i>获取挂机状态失败
            </div>
        `;
    }
}

// 渲染挂机状态
function renderIdleStatus(idleData) {
    const container = document.getElementById('idleStatusInfo');
    
    if (!idleData || !idleData.is_idle) {
        container.innerHTML = `
            <div class="text-center text-muted p-4">
                <i class="fas fa-clock fa-3x mb-3 text-secondary"></i>
                <h6>角色当前处于空闲状态</h6>
                <p class="mb-3">角色将自动开始挂机获取经验和金币</p>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    挂机系统会自动为您的角色积累经验值和金币，无需手动操作
                </div>
            </div>
        `;
        return;
    }
    
    // 从API响应中获取挂机时长和奖励数据
    const durationHours = idleData.duration_hours || 0;
    const maxDurationReached = idleData.max_duration_reached || false;
    
    // 限制显示的最大时长为4小时
    const displayDurationHours = Math.min(durationHours, 4);
    const duration = Math.floor(displayDurationHours * 3600); // 转换为秒数用于formatDuration
    
    const currentRewards = idleData.current_rewards || {};
    const accumulatedExp = currentRewards.exp || 0;
    const accumulatedGold = currentRewards.gold || 0;
    
    const html = `
        <div class="idle-status">
            <div class="row">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-3">
                        <i class="fas fa-clock text-success fa-2x me-3"></i>
                        <div>
                            <h6 class="mb-1">正在挂机中</h6>
                            <small class="text-muted">挂机时长: ${formatDuration(duration)}${maxDurationReached ? ' (已达最大时长)' : ''}</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <div class="card bg-light">
                                <div class="card-body text-center p-2">
                                    <i class="fas fa-star text-warning"></i>
                                    <div class="h5 mb-0">${formatExp(accumulatedExp)}</div>
                                    <small class="text-muted">累计经验</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="card bg-light">
                                <div class="card-body text-center p-2">
                                    <i class="fas fa-coins text-warning"></i>
                                    <div class="h5 mb-0">${accumulatedGold}</div>
                                    <small class="text-muted">累计金币</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 d-flex align-items-center">
                    <button class="btn btn-warning btn-lg w-100" onclick="collectRewards()">
                        <i class="fas fa-gift me-2"></i>
                        <div>收集收益</div>
                        <small class="d-block">继续挂机</small>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}





// 收集挂机收益
async function collectRewards() {
    if (!currentCharacterId) return;
    
    try {
        const response = await apiRequest('/api/idle/collect_rewards', 'POST', {
            character_id: currentCharacterId
        });
        
        if (response.success) {
            showToast(`收集成功！获得 ${formatExp(response.rewards.exp)} 经验，${response.rewards.gold} 金币`, 'success');
            await loadCharacters();
            updateIdleStatus();
        } else {
            showToast(response.message, 'error');
        }
    } catch (error) {
        showToast('收集挂机收益失败', 'error');
    }
}

// 删除角色
async function deleteCharacter(characterId, characterName) {
    // 显示确认对话框
    if (!confirm(`确定要删除角色 "${characterName}" 吗？\n\n此操作不可撤销，角色的所有数据将被永久删除！`)) {
        return;
    }
    
    try {
        const response = await apiRequest(`/api/characters/${characterId}/delete`, 'DELETE');
        
        if (response.success) {
            showToast(response.message, 'success');
            
            // 如果删除的是当前选中的角色，清空选择
            if (String(currentCharacterId) === String(characterId)) {
                currentCharacterId = null;
                document.getElementById('currentCharacterCard').style.display = 'none';
                document.getElementById('idleStatusCard').style.display = 'none';
            }
            
            // 重新加载角色列表
            await loadCharacters();
        } else {
            showToast(response.message, 'error');
        }
    } catch (error) {
        showToast('删除角色失败', 'error');
        console.error('删除角色失败:', error);
    }
}



// 快速收集挂机收益
async function quickCollectRewards(characterId) {
    try {
        console.log('收集收益，角色ID:', characterId);
        const response = await apiRequest('/api/idle/collect_rewards', 'POST', {
            character_id: characterId
        });
        
        if (response.success) {
            showToast(`收集成功！获得 ${formatExp(response.rewards.exp)} 经验，${response.rewards.gold} 金币`, 'success');
            await loadCharacters();
            if (String(currentCharacterId) === String(characterId)) {
                updateIdleStatus();
            }
        } else {
            showToast(response.message, 'error');
            console.error('收集收益失败:', response.message);
        }
    } catch (error) {
        showToast('收集挂机收益失败', 'error');
        console.error('收集收益请求失败:', error);
    }
}



// 创建角色
document.getElementById('createCharacterBtn').addEventListener('click', async function() {
    const form = document.getElementById('createCharacterForm');
    const formData = new FormData(form);
    
    const btn = this;
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>创建中...';
    btn.disabled = true;
    
    try {
        const data = {
            name: formData.get('name'),
            character_class: formData.get('character_class')
        };
        
        const response = await apiRequest('/api/characters/create', 'POST', data);
        
        if (response.success) {
            showToast(response.message, 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('createCharacterModal'));
            modal.hide();
            // 重新加载角色列表
            await loadCharacters();
            // 清空表单
            form.reset();
        } else {
            showToast(response.message, 'error');
        }
    } catch (error) {
        showToast('创建角色失败', 'error');
    } finally {
        btn.innerHTML = originalText;
        btn.disabled = false;
    }
});
</script>
{% endblock %}